import { DownOutlined, UpOutlined } from '@ant-design/icons';
import { Popconfirm, Button, Col, Form, Input, Row, Select, theme, Divider, Radio, Table, Space, Tag, Checkbox, Pagination, Switch, message, Modal } from 'antd';
import { useEffect, useState } from 'react';
// 发送请求函数
import { getReason, changeStateReason, selectReason, del } from '../../../../utils/cbt/sendRequset'
import Edit from '../Eidt';
import Add from '../Add';
const { Option } = Select;// ---表单的内容
// 搜索表单
const AdvancedSearchForm = (props) => {
    const { onDataChange } = props;
    const { token } = theme.useToken();
    const [form] = Form.useForm();
    // // -----模态框
    const [openAdd, setOpenAdd] = useState(false);
    const formStyle = {
        maxWidth: 'none',
        background: token.colorFillAlter,
        borderRadius: token.borderRadiusLG,
        padding: 10,
    };
    // 点击筛选后的数据及请求
    const onFinish = (values) => {
        console.log('Received values of form: ', values);
        selectReason(values).then(res => {
            if (res.code == 200) {
                message.success('查询成功')
                console.log("筛选出来的结果", res);
                const tableData = res.data
                tableData.forEach((item, index) => {
                    // 每个data的都要key
                    tableData[index].key = item.id
                });
                onDataChange(tableData);
                // setData(tableData)
            }
        })
    };
    // 添加
    const add = () => {
        console.log('点击了添加');
        setOpenAdd(true)
    };
    const resetData = () => {
        form.resetFields();
        console.log('点击了重置');
        getMsg()
        message.success('重置成功')
    };
    const getMsg = () => {
        getReason().then(res => {
            console.log("data", res);
            if (res.code == 200) {
                const tableData = res.data
                tableData.forEach((item, index) => {
                    // 每个data的都要key
                    tableData[index].key = item.id
                });
                onDataChange(tableData);
            }
        })
    }
    // 点击取消
    const cancleBtn = () => {
        setOpenAdd(false);
    }
    /**
     * 下拉框数据演示
      const arr=[
          {
              value:0,
              title:'启用'
          },
          {
              value:1,
              title:'禁用'
          }
      ]
     */
    return (<>
        <Form form={form} name="advanced_search" style={formStyle} onFinish={onFinish}
            initialValues={{ reason_state: 2, reason: '' }}
        >
            <Row gutter={22}>
                <Col span={6}>
                    <Form.Item
                        name='reason_state'//初始化动态变得数据
                        label='启用状态'

                    >
                        {/* <Input placeholder="placeholder" /> */}
                        <Select>
                            {/* {
                                arr.map((item,index) =>{
                                    return  <Option value={item.value} key={item.value}>{item.title} </Option>
                                })
                            } */}
                            <Option value={2}>全部</Option>
                            <Option value={0}>启用</Option>
                            <Option value={1}>禁用</Option>
                        </Select>
                    </Form.Item>
                </Col>
                <Col span={6}>
                    <Form.Item
                        name='reason'
                        label='原因'
                        rules={[
                            {
                                message: 'Input something!',
                            },
                        ]}
                    >
                        <Input placeholder="请输入退货原因" />
                    </Form.Item>
                </Col>
            </Row>
            <Row>
                <Col
                    span={22}
                    style={{
                        // textAlign: 'right',
                    }}
                >
                    <Button type="primary"
                        style={{
                            margin: '0 0.8rem',
                        }}
                        onClick={() => {
                            add();
                        }}>

                        添加
                    </Button>
                    <Button type="primary" htmlType="submit"
                    >
                        筛选
                    </Button>
                    <Button
                        style={{
                            margin: '0 .8rem',
                        }}
                        onClick={() => {
                            resetData()
                            // form.resetFields();
                        }}
                    >
                        重置
                    </Button>
                    {/* <a
                        style={{
                            fontSize: 12,
                        }}
                        onClick={() => {
                            setExpand(!expand);
                        }}
                    >
                        {expand ? <UpOutlined /> : <DownOutlined />} 展开
                    </a> */}
                </Col>
            </Row>
        </Form>

        {/* 模态框 */}
        <Add open={openAdd} cancleBtn={cancleBtn} getMsg={getMsg}></Add>
    </>

    );
};
// ----以下是表格
// 表格
const TableDetail = (props) => {
    // ---------表格
    const { data, onDataChange, delDataChange, delData } = props;
    // // -----模态框
    const [open, setOpen] = useState(false);
    const [eidtData, setEidtData] = useState()
    const [localData, setLocalData] = useState(delData);
    useEffect(() => {
        getMsg()
    }, [])
    // 发送请求渲染数据
    const getMsg = () => {
        getReason().then(res => {
            if (res.code == 200) {
                const tableData = res.data
                tableData.forEach((item, index) => {
                    // 每个data的都要key
                    tableData[index].key = item.id
                });
                onDataChange(tableData);
            }
        })
    }

    // 表头
    const columns = [
        {
            title: '原因描述',
            dataIndex: 'reason',
            key: 'reason',
            // render: (text) => <a>{text}</a>,
        },
        {
            title: '添加时间',
            dataIndex: 'reason_create_time',
            key: 'reason_create_time',
        },
        {
            title: '是否启用',
            dataIndex: 'reason_state',
            key: 'reason_state',
            render: (_, record) => <Switch checked={record.reason_state == 0 ? 'checked' : ''} onChange={() => onChange(record)} />
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <a onClick={() => eidtReason(record)}>
                        编辑
                    </a>
                </Space>
            ),
        },
    ];

    useEffect(() => {
        delDataChange(localData)
    }, [localData]);
    // 选择的数组
    const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
            console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
            setLocalData(selectedRowKeys)
        },
    };
    // switch
    const onChange = (record) => {
        const data = { id: record.id, state: record.reason_state }
        if (record.reason_state) {
            changeStateReason(data).then(res => {
                if (res.code == 200) {
                    message.success('修改状态成功')
                    getMsg()
                }
            })

        } else {
            changeStateReason(data).then(res => {
                if (res.code == 200) {
                    message.success('修改状态成功')
                    getMsg()
                }
            })
        }
    };

    // 点击编辑
    const eidtReason = (record) => {
        console.log("点击了编辑", record);
        setOpen(true);
        setEidtData(record)
    }
    // 点击取消
    const cancleBtn = () => {
        setOpen(false);
    }

    return (
        <>
            <Table rowSelection={{
                type: 'checkbox',
                ...rowSelection,
            }} columns={columns} dataSource={data}
                pagination={{
                    pageSize: 4
                }} />
            <Edit open={open} cancleBtn={cancleBtn} eidtData={eidtData} getMsg={getMsg}></Edit>
        </>
    )

};



const App = () => {
    const [data, setData] = useState([])
    const [delData, setDelData] = useState()//批量删除的数据
    // 更改表格数据
    const handleDataChange = (newData) => {
        setData(newData);
    }
    useEffect(() => {
        setDelData(delData)
        // console.log("批量删除的数据",delData);
    }, [delData]);
    // 批量删除更改
    const delDataChange = (newData) => {
        setDelData(newData)
    }

    const { token } = theme.useToken();
    const listStyle = {
        textAlign: 'center',
        background: token.colorFillAlter,
        borderRadius: token.borderRadiusLG,
        marginTop: 16,
    };
    const handleChange = (value) => {
        console.log(`selected ${value}`);
    };
    const [selectionType, setSelectionType] = useState('checkbox');
    const delAll = () => {
        setOpenDel(true)
    }
    // ------确认删除的模态框
    const [openDel, setOpenDel] = useState(false)
    const handleOkDel = () => {
        console.log('确认');
        console.log('点击了批量删除', delData.toString());
        const obj = {}
        obj.id = delData.toString()//数组转化为字符串
        del(obj).then(res => {
            if (res.code == 200) {
                message.success('批量删除成功')
                getReason().then(res => {
                    console.log("data", res);
                    if (res.code == 200) {
                        const tableData = res.data
                        tableData.forEach((item, index) => {
                            // 每个data的都要key
                            tableData[index].key = item.id
                        });
                        handleDataChange(tableData);
                        setOpenDel(false)
                    }
                })

            } else {
                message.error('删除成功')

            }
        })
    };
    const handleCancelDel = () => {
        console.log('取消');
        setOpenDel(false);
    };
    return (
        <div>
            <AdvancedSearchForm onDataChange={handleDataChange} />
            <div style={listStyle}>
                <div style={{ lineHeight: '2rem', display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', height: '2rem', padding: '1rem' }}>
                    <h3>数据列表</h3>
                    <div>
                        <a onClick={() => delAll()}>批量删除</a>
                        {/* <Select
                            defaultValue="批量操作"
                            onChange={handleChange}
                            options={[
                                { value: {0}, label: '批量删除' },
                                // { value: 'lucy', label: '批量XX' },
                            ]}
                        /> */}
                    </div>
                </div>

                <div style={{ lineHeight: '20rem', }}>
                    <Divider />
                    <TableDetail data={data} onDataChange={handleDataChange} delDataChange={delDataChange} delData={delData} />
                </div>

                {/* 点击删除的模态框 */}
                <Modal
                    open={openDel}
                    title="提示"
                    onOk={handleOkDel}
                    onCancel={handleCancelDel}
                    footer={[
                        <Button key="back" onClick={handleCancelDel}>
                            取消
                        </Button>,
                        <Button key="submit" type="primary" onClick={handleOkDel}>
                            确定
                        </Button>
                    ]}
                >
                    <p>确认删除？</p>
                </Modal>

            </div>
        </div >
    );
};
export default App;